﻿using System;
using System.Web;
using System.Web.Mvc;

namespace Nasa8x.Mvc.Helpers.Attributes
{
    public class CacheAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Length of time (in seconds) to cache response.
        /// </summary>
        public double Duration { get; set; }

        /// <summary>
        /// Specify a text string to vary cached output responses by.
        /// </summary>
        public string VaryBy { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var cache = filterContext.HttpContext.Response.Cache;

            
            TimeSpan cacheTime = TimeSpan.FromSeconds( Duration>0?Duration: 30);

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(cacheTime));
            cache.SetMaxAge(cacheTime);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

            if (!string.IsNullOrEmpty(VaryBy)) cache.SetVaryByCustom(VaryBy);

            base.OnActionExecuting(filterContext);
        }
    }
}
